package me.firstapp.bbs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import me.firstapp.bbs.base.BaseController;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.JsonAdvertisement;
import me.firstapp.common.module.bbs.JsonCollection;
import me.firstapp.common.module.bbs.JsonMember;
import me.firstapp.common.module.bbs.JsonPointAccount;
import me.firstapp.common.module.bbs.JsonReply;
import me.firstapp.common.module.bbs.JsonSection;
import me.firstapp.common.module.bbs.JsonTopic;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.spi.bbs.AdvertisementService;
import me.firstapp.spi.bbs.CollectionService;
import me.firstapp.spi.bbs.ReplyService;
import me.firstapp.spi.bbs.SectionService;
import me.firstapp.spi.bbs.TopicService;
import me.firstapp.spi.shop.PointService;

@Controller
@RequestMapping("/topic")
public class TopicController extends BaseController {

	@Autowired
	private SectionService sectionService;

	@Autowired
	private TopicService topicService;

	@Autowired
	private ReplyService replyService;

	@Autowired
	private CollectionService collectionService;

	@Autowired
	private PointService pointService;

	@Autowired
	private AdvertisementService advertisementService;
	
	@Value("#{configProperties['bbs.url']}")
	private String bbsUrl;
	
	@Value("#{configProperties['share.image.url']}")
	private String shareImage;

	@RequestMapping(value = "/addTopicView")
	public ModelAndView addTopicView(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		ListObject<JsonSection> result = sectionService.findSectionList();
		modelMap.put("sections", result.getItems());
		return new ModelAndView("topic/createTopic", modelMap);
	}

	@RequestMapping(value = "/updateTopicView")
	public ModelAndView updateTopicView(Long topicId, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		SingleObject<JsonTopic> result = topicService.findTopic(topicId);
		modelMap.put("topic", result.getObject());
		return new ModelAndView("topic/updateTopic", modelMap);
	}

	@RequestMapping(value = "/updateTopic", method = RequestMethod.POST)
	public String updateTopic(Long topicId, String summary, String content, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributesModelMap modelMap) {
		JsonMember member = null;
		if (!modelMap.containsAttribute("member")) {
			member = getLoginMember(request, response);
		} else {
			member = (JsonMember) modelMap.get("member");
		}
		if (member != null) {
			SingleObject<JsonTopic> result = topicService.updateTopic(topicId, summary, content, null, null, null, null,
					null);
			JsonTopic topic = result.getObject();
			modelMap.addFlashAttribute("topic", topic);
			modelMap.addAttribute("topicId", topic.getId());
			return "redirect:/topic/{topicId}";
		} else {
			return "redirect:/";
		}
	}

	@RequestMapping(value = "/addTopic", method = RequestMethod.POST)
	public String addTopic(Long sectionId, String title, String summary, String content, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributesModelMap modelMap) {
		JsonMember member = null;
		if (!modelMap.containsAttribute("member")) {
			member = getLoginMember(request, response);
		} else {
			member = (JsonMember) modelMap.get("member");
		}
		if (member != null) {
			SingleObject<JsonTopic> result = topicService.addTopic(member.getId(), sectionId, title, summary, content);
			JsonTopic topic = result.getObject();
			modelMap.addFlashAttribute("topic", topic);
			modelMap.addAttribute("topicId", topic.getId());
			return "redirect:/topic/{topicId}";
		} else {
			return "redirect:/";
		}
	}

	@RequestMapping(value = "/{topicId}", method = RequestMethod.GET)
	public ModelAndView showTopicDetail(@PathVariable Long topicId, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		JsonTopic topic = null;
		if (!modelMap.containsAttribute("topic")) {
			SingleObject<JsonTopic> result = topicService.findTopic(topicId);
			topic = result.getObject();
			modelMap.put("topic", topic);
		} else {
			topic = (JsonTopic) modelMap.get("topic");
		}
		
		if(topic == null){
			throw new ServiceException(StatusHouse.TOPIC_NOT_EXIST);
		}

		// 作者信息
		JsonMember author = topic.getMember();
		if (author != null) {
			SingleObject<Long> result = collectionService.findCollectionCounts(author.getId(), null, null);
			Long colCounts = result.getObject();
			SingleObject<Long> topicCountsResult = topicService.findMemberTopicsCounts(author.getId());
			Long topicCounts = topicCountsResult.getObject();
			ListObject<JsonTopic> othersResult = topicService.findSomeTopics(author.getId(), null, 8);
			List<JsonTopic> others = othersResult.getItems();
			for (JsonTopic jsonTopic : others) {
				if (jsonTopic.getId().equals(topicId)) {
					others.remove(jsonTopic);
					break;
				}
			}
			modelMap.put("otherTopics", others);
			modelMap.put("colCounts", colCounts);
			modelMap.put("topicCounts", topicCounts);
		}

		// 回复列表
		PageObject<JsonReply> replyResult = replyService.findReplyPage(1, 500, topicId, null);
		modelMap.put("replyPage", replyResult.getPage());
		List<Integer> pages = new ArrayList<Integer>();
		for (int i = 1; i <= replyResult.getPage().getTotalPage(); i++) {
			pages.add(i);
		}
		modelMap.put("pages", pages);

		// 回复数量
		SingleObject<Long> replyCounts = replyService.findTopicReplyCounts(topicId);
		modelMap.put("replyCounts", replyCounts.getObject());

		// 收藏标志
		Long memberId = getLoginMemberId(request, response);
		if (memberId != null) {
			SingleObject<JsonCollection> result = collectionService.findMemberTopicCollectionRel(memberId, topicId);
			JsonCollection apiJsonCollection = result.getObject();
			if (apiJsonCollection == null) {
				modelMap.put("isCollect", false);
			} else {
				modelMap.put("isCollect", true);
			}
		}
		modelMap.put("bbsUrl", bbsUrl);
		modelMap.put("shareImage", shareImage);
		return new ModelAndView("topic/topicDetail", modelMap);
	}

	@RequestMapping(value = "/addReply.do", method = RequestMethod.POST)
	public void addReply(String content, Long topicId, Long toMemberId, Long defaultToMemberId,
			HttpServletRequest request, HttpServletResponse response, RedirectAttributesModelMap modelMap) {
		Long memberId = getCurrentLoginMemberId(request, response);
		if (toMemberId == null) {
			toMemberId = defaultToMemberId;
		}
		SingleObject<JsonReply> result = replyService.addReply(content, topicId, memberId, toMemberId);
		JsonReply apiJsonReply = result.getObject();
		if (apiJsonReply != null) {
			apiJsonReply.setFormatCreateTime(apiJsonReply.formatDate(apiJsonReply.getCreateTime()));
			apiJsonReply.setContent(apiJsonReply.markedownToHtml(apiJsonReply.getContent()));
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/findReplyPage.do", method = RequestMethod.GET)
	public void findReplyPage(@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize, Long topicId,
			HttpServletRequest request, HttpServletResponse response) {
		PageObject<JsonReply> result = replyService.findReplyPage(pageNo, 500, topicId, null);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/sections")
	public ModelAndView sectionsView(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		ListObject<JsonSection> result = sectionService.findSectionList();
		modelMap.put("sections", result.getItems());
		modelMap.put("navFlag", 1);
		return new ModelAndView("topic/sections", modelMap);
	}

	@RequestMapping(value = "/sectionTopics", method = RequestMethod.GET)
	public ModelAndView sectionTopics(
			@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "20") Integer pageSize, Long sectionId,
			String sectionName, Integer recommend, String sortParam, String sortType, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		modelMap.put("sectionId", sectionId);
		modelMap.put("sectionName", sectionName);
		Integer searchType = 0;
		if (recommend != null && recommend == 1) {
			searchType = 1;
		}
		if ("DESC".equals(sortType)) {
			searchType = 2;
		}
		if ("ASC".equals(sortType)) {
			searchType = 3;
		}
		modelMap.put("searchType", searchType);
		// 话题
		PageObject<JsonTopic> topicPage = topicService.findTopicsPage(pageNo, pageSize, sectionId, null, recommend,
				sortParam, sortType);
		List<Integer> pages = new ArrayList<Integer>();
		for (int i = 1; i <= topicPage.getPage().getTotalPage(); i++) {
			pages.add(i);
		}
		modelMap.put("topicPage", topicPage.getPage());
		modelMap.put("pages", pages);

		// 用户
		JsonMember member = null;
		if (modelMap.containsAttribute("member")) {
			member = (JsonMember) modelMap.get("member");
		} else {
			member = getLoginMember(request, response);
		}

		if (member != null) {
			// 积分余额
			SingleObject<JsonPointAccount> accountResult = pointService.findPointAccount(member.getId());
			JsonPointAccount pointAccount = accountResult.getObject();
			modelMap.put("points", pointAccount == null ? 0 : pointAccount.getCurrentValue());
			// 帖子数
			SingleObject<Long> result = topicService.findMemberTopicsCounts(member.getId());
			Long topicCounts = result.getObject();
			modelMap.put("topicCounts", topicCounts == null ? 0 : topicCounts);
			// 收藏数
			SingleObject<Long> collectResult = collectionService.findCollectionCounts(member.getId(), null, null);
			Long colCounts = collectResult.getObject();
			modelMap.put("colCounts", colCounts == null ? 0 : colCounts);
		}

		// 广告
		ListObject<JsonAdvertisement> adResult = advertisementService.findAvailableAds();
		List<JsonAdvertisement> ads = adResult.getItems();
		if (!ads.isEmpty()) {
			request.setAttribute("ad", ads.get(0));
		}
		return new ModelAndView("topic/sectionTopics", modelMap);
	}

	@RequestMapping(value = "/changCollectionStatus.do", method = RequestMethod.POST)
	public void changCollectionStatus(Long topicId, Boolean isCollection, HttpServletRequest request,
			HttpServletResponse response) {
		Long memberId = getCurrentLoginMemberId(request, response);
		SingleObject<Boolean> result = collectionService.changCollectionStatus(memberId, topicId, null, 0,
				isCollection);
		ResponseUtils.renderJson(response, result);
	}

}
